Multiply Strings

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note:

  • The numbers can be arbitrarily large and are non-negative.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

Solution:

  1. public class Solution {
  2. public String multiply(String num1, String num2) {
  3. if (num1 == null || num2 == null || num1.length() == 0 || num2.length() == 0) {
  4. return "";
  5. }
  6. char[] chs1 = num1.toCharArray();
  7. char[] chs2 = num2.toCharArray();
  8. reverse(chs1, 0, chs1.length - 1);
  9. reverse(chs2, 0, chs2.length - 1);
  10. int n = chs1.length;
  11. int m = chs2.length;
  12. // total length won't be longer than m + n
  13. int[] res = new int[m + n];
  14. for (int i = 0; i < n; i++) {
  15. int val = 0;
  16. int d1 = (int)(chs1[i] - '0');
  17. for (int j = 0; j < m; j++) {
  18. int d2 = (int)(chs2[j] - '0');
  19. val = d1 * d2 + res[i + j] + val;
  20. res[i + j] = val % 10;
  21. val /= 10;
  22. }
  23. if (val > 0) {
  24. res[i + m] = val;
  25. }
  26. }
  27. StringBuilder sb = new StringBuilder();
  28. boolean valid = false;
  29. for (int i = res.length - 1; i >= 0; i--) {
  30. // ignore leading zeros
  31. if (!valid && res[i] == 0) {
  32. continue;
  33. }
  34. valid = true;
  35. sb.append(res[i]);
  36. }
  37. if (sb.length() == 0) {
  38. return "0";
  39. }
  40. return sb.toString();
  41. }
  42. void reverse(char[] chs, int lo, int hi) {
  43. while (lo < hi) {
  44. swap(chs, lo++, hi--);
  45. }
  46. }
  47. void swap(char[] chs, int i, int j) {
  48. char ch = chs[i];
  49. chs[i] = chs[j];
  50. chs[j] = ch;
  51. }
  52. }